package com.ht.module.info.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ht.constant.DicConstants;
import com.ht.module.info.entity.InfoGoods;
import com.ht.module.info.entity.InfoMerchants;
import com.ht.module.info.entity.InfoOrder;
import com.ht.module.info.entity.InfoOrderDetails;
import com.ht.module.info.mapper.InfoOrderDetailsMapper;
import com.ht.module.info.mapper.InfoOrderMapper;
import com.ht.module.info.service.IInfoGoodsService;
import com.ht.module.info.service.IInfoMerchantsService;
import com.ht.module.info.service.IInfoOrderDetailsService;
import com.ht.module.info.service.IInfoOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.module.sys.entity.SysUser;
import com.ht.module.sys.service.ISysMenuService;
import com.ht.module.vo.MaterialNumVo;
import com.ht.util.CommMethod;
import com.ht.util.DateUtil;
import com.ht.util.Pager;
import com.ht.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Auto-generator
 * @since 2021-12-03
 */
@Service
public class InfoOrderServiceImpl extends ServiceImpl<InfoOrderMapper, InfoOrder> implements IInfoOrderService {
    @Autowired
    private IInfoOrderDetailsService infoOrderDetailsService;
    @Resource
    private InfoOrderDetailsMapper infoOrderDetailsMapper;
    @Autowired
    private IInfoGoodsService infoGoodsService;
    @Autowired
    private IInfoMerchantsService infoMerchantsService;
    @Override
    public void add(InfoOrder infoOrder) {

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        //订单编号
        String code = df.format(LocalDateTime.now()) + UserUtil.getUserId();
        //查询出所有商品
        List<InfoGoods> goodsList = infoGoodsService.list(
                new QueryWrapper<InfoGoods>()
                        .in("id", infoOrder.getDetails().stream().map(InfoOrderDetails::getGoodsId).collect(Collectors.toList()))
        );
        //生成多个订单，一家店铺一个订单
        Map<String, List<InfoGoods>> collect = goodsList.stream().collect(Collectors.groupingBy(InfoGoods::getMerchantsId));
        for (String key : collect.keySet()) {
            //创建订单
            InfoOrder row = new InfoOrder()
                    .setId(IdWorker.getIdStr())
                    .setCode(code)
                    .setShippingAddress(infoOrder.getShippingAddress())
                    .setLat(infoOrder.getLat())
                    .setLng(infoOrder.getLng())
                    .setReceipt(infoOrder.getReceipt())
                    .setReceiptPhone(infoOrder.getReceiptPhone())
                    .setRemarks(infoOrder.getRemarks())
                    .setNote(infoOrder.getNote())
                    .setDeliveryDate(infoOrder.getDeliveryDate())
                    .setState(DicConstants.OrderState.PREPARE)
                    .setMerchantsId(key);
            CommMethod.beanCreate(row);
            List<InfoGoods> goodsTemp = collect.get(key);
            List<InfoOrderDetails> detailsList = new ArrayList<>();
            for (InfoGoods goods : goodsTemp) {
                String number = infoOrder.getDetails().stream().filter(x -> x.getGoodsId().equals(goods.getId())).findFirst().get().getNumber();
                InfoOrderDetails details = new InfoOrderDetails()
                        .setOrderId(row.getId())
                        .setGoodsId(goods.getId())
                        .setMerchantsId(goods.getMerchantsId())
                        .setNumber(number)
                        .setTotalPrice(goods.getPrice().multiply(new BigDecimal(number)));
                CommMethod.beanCreate(details);
                detailsList.add(details);
            }
            infoOrderDetailsService.saveBatch(detailsList);

            //计算订单总价
            row.setTotalPrice(new BigDecimal(detailsList.stream().mapToDouble(x -> x.getTotalPrice().doubleValue()).sum() + ""));
            baseMapper.insert(row);
        }

    }

    @Override
    public Pager<InfoOrder> findPageByMe(Pager<InfoOrder> pager, InfoOrder infoOrder) {
        QueryWrapper<InfoOrder> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(infoOrder.getCode())) {
            qw.eq("code", infoOrder.getCode());
        }
        qw.eq("create_user", UserUtil.getUserId());
        return baseMapper.selectPage(pager, qw);
    }

    @Override
    public Pager<InfoOrder> findPageByMerchants(Pager<InfoOrder> pager, InfoOrder infoOrder) {
        QueryWrapper<InfoOrder> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(infoOrder.getCode())) {
            qw.eq("code", infoOrder.getCode());
        }
        //查询出当前用户对应的商户
        InfoMerchants merchants = infoMerchantsService.getOne(
                new QueryWrapper<InfoMerchants>()
                        .eq("user_id", UserUtil.getUserId())
        );
        if(merchants==null){
            qw.eq("merchants_id","-1");
        }else{
            qw.eq("merchants_id",merchants.getId());
        }
        return baseMapper.selectPage(pager, qw);
    }

    @Override
    public InfoOrder findById(String id) {
        InfoOrder infoOrder = baseMapper.findById(id);
        //查询订单详情
        if (infoOrder != null) {
            QueryWrapper<InfoOrderDetails> qw = new QueryWrapper<>();
            infoOrder.setDetails(
                    infoOrderDetailsMapper.findList(
                    qw.eq("order_id", id)
            ));
        }
        return infoOrder;
    }

    @Override
    public void updateState(String id, String val) {
        InfoOrder info=new InfoOrder();
        info.setId(id);
        info.setState(val);
        CommMethod.beanUpdate(info);
        baseMapper.updateById(info);
    }


}
